const tenpay = require('tenpay');
let config = require('../config/config');
const configs = {
    appid: config.appid,
    mchid: config.mchid,
    partnerKey: config.partnerKey,
    notify_url: config.notify_url,
};
const api = new tenpay(configs);
let md5 = require('../libs/md5');
let leancloudUtils = require('../utils/LeanCloudUtils');
let AV = require('leancloud-storage');
module.exports = {
    //产生随机数
    randomWord: function (randomFlag, min, max) {
        let str = "",
            range = min,
            arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        if (randomFlag) {
            range = Math.round(Math.random() * (max - min)) + min;
        }
        for (var i = 0; i < range; i++) {
            let pos = Math.round(Math.random() * (arr.length - 1));
            str += arr[pos];
        }
        return str;
    },

    //发起抽奖支付
    async doPayment(req, res, next){
        console.log(req.body);
        let orderId = req.body.order_id;
        let body = req.body.body;
        let totalFee = req.body.total_fee;
        let openId = req.body.open_id;
        let result = await api.unifiedOrder({
            out_trade_no: orderId,
            body: body,
            total_fee: totalFee,
            openid: openId,
        });
        console.log(result);
        if (result.result_code === 'SUCCESS') {
            let random = module.exports.randomWord(false, 32);
            let time = new Date().getTime();
            let prepay_id = result.prepay_id;
            let order_id = result.order_id;
            let stringA = 'appId=' + config.appid +
                '&nonceStr=' + random +
                '&package=prepay_id=' + result.prepay_id +
                '&signType=' + 'MD5' +
                '&timeStamp=' + time;
            let stringAddKey = stringA + "&key=" + config.partnerKey
            let md5Result = md5(stringAddKey).toUpperCase();
            res.send({
                code: '0',
                data: {
                    timeStamp: time + '',
                    nonceStr: random,
                    package: 'prepay_id=' + prepay_id,
                    signType: 'MD5',
                    paySign: md5Result,
                    orderId: order_id,
                }
            })
        }
        else {
            console.log(result);
            res.send({
                code: '1',
                msg: '发起支付失败',
                data: result,
            })
        }
    },


    async doShippingPayment(req, res, next){
        let orderId = req.body.order_id;
        let body = req.body.body;
        let totalFee = req.body.total_fee;
        let openId = req.body.open_id;
        let result = await api.unifiedOrder({
            out_trade_no: orderId,
            body: body,
            total_fee: totalFee,
            openid: openId,
        });
        console.log(result);
        if (result.result_code === 'SUCCESS') {
            let random = module.exports.randomWord(false, 32);
            let time = new Date().getTime();
            let prepay_id = result.prepay_id;
            let order_id = result.order_id;
            let stringA = 'appId=' + config.appid +
                '&nonceStr=' + random +
                '&package=prepay_id=' + result.prepay_id +
                '&signType=' + 'MD5' +
                '&timeStamp=' + time;
            let stringAddKey = stringA + "&key=" + config.partnerKey
            let md5Result = md5(stringAddKey).toUpperCase();
            res.send({
                code: '0',
                data: {
                    timeStamp: time + '',
                    nonceStr: random,
                    package: 'prepay_id=' + prepay_id,
                    signType: 'MD5',
                    paySign: md5Result,
                    orderId: order_id,
                }
            })
        }
        else {
            console.log(result);
            res.send({
                code: '1',
                msg: '发起支付失败',
                data: result,
            })
        }
    },

    async call(req, res, next){
        res.send({
            code: '1',
            msg: '发起支付失败',
            data: "111",
        })
    },

    async callback(req, res, next){
        console.log("返回数据");
        console.log(req.body.xml);



        if (req.body.xml.result_code === 'SUCCESS') {
            try {
                let orderId = req.body.xml.out_trade_no;
                let orderQuery = new AV.Query('Order');
                orderQuery.equalTo("ordernum", orderId);
                let orderResult = await orderQuery.find();
                console.log("lean数据");
                console.log(orderResult);
                if (orderResult.length) {
                    orderResult[0].set("payment", true);
                    orderResult[0].save();

                    let hotGoodsId = orderResult[0].get("goodsId");
                    var table='HotGoods'
                    if(orderResult[0].get("goodsType")=='hot'){

                    }

                    let uid = orderResult[0].get("uid");
                    let stepCoin = orderResult[0].get("stepCoin")*-1;
                    let userQuery = new AV.Query('UserInfo');
                    let user = await userQuery.get(uid);
                    console.log("user");
                    console.log(user);
                    var adddata = {
                        uid: user.get("objectId"),
                        nickName: user.get("nickName"),
                        avatarUrl: user.get("avatarUrl"),
                    }
                    var goods = AV.Object.createWithoutData(table,hotGoodsId);
                    goods.add('join',adddata);
                    goods.save().then(function (goods) {
                        goods.increment('inventory', -1);
                        goods.fetchWhenSave(true);
                        return goods.save();
                    }).then(function (res) {
                        console.log("goods刷新了");
                    }, function (error) {
                        // 异常处理
                    });


                    // var user = AV.Object.createWithoutData('UserInfo',uid);
                    user.save().then(function (user) {
                        user.increment('stepCoin', Number(stepCoin));
                        user.fetchWhenSave(true);
                        return user.save();
                    }).then(function (res) {
                        console.log("user刷新了");
                    }, function (error) {
                        // 异常处理
                    });



                    // let prizeList = orderResult[0].get("prizelist");
                    // prizeList.forEach(async (item) => {
                    //     let objectId = item.objectId;
                    //     let recordQuery = new AV.Query('Record');
                    //     let record = await recordQuery.get(objectId);
                    //     if (record) {
                    //         record.set("ticket", true);
                    //         record.save();
                    //     }
                    // });

                }




                //如果是抽奖订单
                // let recordQuery = new AV.Query('Record');
                // recordQuery.equalTo('recordnum', orderId);
                // let recordResult = await recordQuery.find();
                // if (recordResult.length) {
                //     //更改订单信息
                //     recordResult[0].set("payment", true);
                //     recordResult[0].save();
                //     //更改用户信息
                //     let uid = recordResult[0].get("uid");
                //     let userQuery = new AV.Query('UserInfo');
                //     let user = await userQuery.get(uid);
                //     console.log("user");
                //     console.log(user);
                //     let leftIntegral = user.get("integral") - recordResult[0].get("integral");
                //     user.set("integral", leftIntegral);
                //     user.set("joinNum", user.get("joinNum") + 1);
                //     if (recordResult[0].get("integral") > 0) {
                //         let jfRecord = {
                //             d: module.exports.randomWord(false, 10),   //随机生成10位数id
                //             type: 3,    //type 1成功邀请 2成功分销  3购买盒子使用
                //             value: recordResult[0].get("integral"), //积分值
                //             time: new Date() //时间 格式new Date()
                //         };
                //         user.add("jfRecord", jfRecord);
                //     }
                //     //如果存在有上级
                //     if (user.get("parentId")) {
                //         let parentUser = await new AV.Query('UserInfo').get(user.get("parentId"));
                //         console.log("parent");
                //         console.log(parentUser);
                //         parentUser.set("integral", parentUser.get("integral") + parseInt(recordResult[0].get("price") * 0.15));
                //         let jfRecord = {
                //             d: module.exports.randomWord(false, 10),   //随机生成10位数id
                //             type: 2,    //type 1成功邀请 2成功分销  3购买盒子使用
                //             value: parseInt(recordResult[0].get("price") * 0.15), //积分值
                //             time: new Date() //时间 格式new Date()
                //         };
                //         parentUser.add("jfRecord", jfRecord);
                //         parentUser.save();
                //     }
                //     user.save();
                //     console.log()
                // }

            }
            catch (e) {
                console.log(e)
            }
            res.send(`<xml>
                       <return_code><![CDATA[SUCCESS]]></return_code>
                       <return_msg><![CDATA[OK]]></return_msg>
                    </xml>`);
        }
        else {

        }
    },
};